package com.yuqih.common.web;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yuqih.common.servlet.RequestContext;

public class RequestMappingAspect {

	private RequestContext requestContext;

	public Object round(ProceedingJoinPoint joinPoint) throws Throwable {

		requestContext.setHandlerClass(joinPoint.getSignature().getDeclaringType().getName());
		if (joinPoint instanceof MethodInvocationProceedingJoinPoint) {
			MethodInvocationProceedingJoinPoint methodJoinPoint = (MethodInvocationProceedingJoinPoint) joinPoint;
			MethodSignature methodSignature = (MethodSignature) methodJoinPoint.getSignature();
			requestContext.setHandlerMethod(methodSignature.getMethod().toString());
			
			ResponseBody responseBody = methodSignature.getMethod().getAnnotation(ResponseBody.class);
			requestContext.setResponseBody(responseBody != null);
		}
		try {
			Object result = joinPoint.proceed();
			if (requestContext.isResponseBody() && requestContext.getResponseObject() == null) {
				requestContext.setResponseObject(result);
			}
			return result;
		} catch (Exception ex) {
			if (requestContext.getError() == null) {
				requestContext.setError(ex);
			}
			throw ex;
		}
	}

	/**
	 * @param requestContext
	 *            the requestContext to set
	 */
	public void setRequestContext(RequestContext requestContext) {
		this.requestContext = requestContext;
	}

}
